from socket import *
import sys
import time

#具体功能实现
class FtpClient(object):
    def __init__(self,s):
        self.s = s
    
    def do_list(self):
        self.s.send(b'L')   #发送请求
        #等待回复
        data = self.s.recv(128).decode()
        if data == 'ok':
            while True:
                file = self.s.recv(1024).decode()
                if file == '##':
                    break
                print(file)
        else:
            #无法操作
            print(data)

    def do_quit(self):
        self.s.send(b'Q')
        self.s.close()
        sys.exit('谢谢使用')

    def do_get(self,filename):
        #发送请求
        self.s.send(('G '+filename).encode())
        data = self.s.recv(128).decode()
        if data == 'ok':
            with open(filename,'wb') as fw:
                while True:
                    data = self.s.recv(1024)
                    if data == b'##':
                        break
                    fw.write(data)
            print('%s下载完成'%filename)
        else:
            print(data)
    
    def do_put(self,filename):
        try:
            fr = open(filename,'rb')
        except:
            print('文件不存在')
            return
        #发送请求
        self.s.send(('P '+filename).encode())
        data = self.s.recv(128).decode()
        if data == 'ok':
            while True:
                data = fr.read(1024)
                if not data:
                    time.sleep(0.1)
                    self.s.send(b'##')
                    break
                self.s.send(data)
            fr.close()
            print('%s文件上传完成'%filename)
        else:
            print(data)
                
#网络联接
def main():
    if len(sys.argv) < 3:
        print('argv is error')
        return
    Host = sys.argv[1]
    Port = int(sys.argv[2])
    Addr = (Host,Port)

    s = socket()
    try:
        s.connect(Addr)
    except Exception as e:
        print('连接服务器失败:',e)
        return

    #创建类对象
    ftp = FtpClient(s)
    
    while True:
        print('\n==========命令选项=========')
        print('****       list        ****')
        print('****      get file     ****')
        print('****      put file     ****')
        print('****        quit       ****')
        print('===========================\n')

        cmd = input('输入命令:')
        if cmd.strip() == 'list':
            ftp.do_list()
        elif cmd.strip() == 'quit':
            ftp.do_quit()
        elif cmd[:3].strip() == 'get':
            #获取文件名
            filename = cmd.split(' ')[-1]
            ftp.do_get(filename)
        elif cmd[:3].strip() == 'put':
            #获取文件名
            filename = cmd.split(' ')[-1]
            ftp.do_put(filename)
        else:
            print("请输入正确命令")
main()